package com.example.demosystem.web;

import com.example.demosystem.dto.req.SendEmailReqDto;
import com.example.demosystem.dto.res.SendEmailResDto;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;

@Slf4j
@RestController
@RequestMapping("")
public class HomeController {

    @Resource
    private JavaMailSender javaMailSender;

    @GetMapping("")
    public String index() {
        return "Hello World!";
    }

    @PostMapping("/send/email/captcha")
    public SendEmailResDto sendEmail(@RequestBody SendEmailReqDto dto) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, false);

            helper.setFrom("noreply@xsunlight.club", "noreply");
            helper.setTo("kangeneral@126.com");
            helper.setSubject("Hello");
            helper.setText("Hello World!", true);
            javaMailSender.send(message);
        } catch (Exception e) {
            log.error("send email error", e);
            return SendEmailResDto.builder()
                    .success(false)
                    .message("send email error:"+e.getMessage())
                    .build();
        }
        return SendEmailResDto.builder()
                .success(true)
                .message("ok")
                .build();
    }
}
